using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using TrainGame.Model;

namespace _1830.UI
{
	/// <summary>
	/// Summary description for GameResults.
	/// </summary>
	public partial class GameStatus : System.Web.UI.Page
	{
	
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		protected void Page_Load(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			string	sPlayer = Session["PlayerName"].ToString ();
			Player	player	= game.Players[sPlayer];

			SetTitle(sPlayer);

			Status.Text ="";

            if (game.BankruptcyOccurred)
            {
                BankMoney.Text = game.ForcedStockSalePlayer.Name + " went bankrupt and the game is over!";
            }
            else
            {
                if (!game.BankBusted)
                    BankMoney.Text = "The Bank has $" + game.Bank.ToString() + " remaining.";
                else
                    BankMoney.Text = "The Bank is broke and there are " + game.NumberOfOperatingRoundsLeft.ToString() + " operating rounds left before the game ends.";
            }

            if (game.GameOver)
            {
                Status.Text = "Thank you for playing 1856.  The game is now over and here are the final results.";
                Back.Enabled = false;
            }

            FillTableWithCompanyInfo();
			FillTableWithPlayerInfo();
		}

		private void SetTitle (string sNewTitle)
		{
			HtmlGenericControl title = this.FindControl ("Title") as HtmlGenericControl;

			if (title != null)
				title.InnerText = sNewTitle;
		}

		private void FillTableWithPlayerInfo ()
		{
			int			nRow		= 0;
			int			nCash		= 0;
			int			nMaxScore	= 0;
			int			nStockTotal	= 0;
			int			nGrandTotal	= 0;
			int			nPrevIndex	= 0;
			Game		game		= Global.getGame (this);;
			bool[]		bSelected	= new bool[game.Players.Count];
			string		sPlayer		= Session["PlayerName"].ToString ();
			Player		nextPlayer	= null;
			Player[]	players		= new Player[game.Players.Count];

			// sort players by highest value
			for (int i = 0; i < game.Players.Count; i++)
			{
				nMaxScore	= 0;
				nPrevIndex	= -1;
				
				for (int j = 0; j < game.Players.Count; j++)
				{
					Player player = game.Players[j];
					
					if (!bSelected[j])
					{
						player.GetPlayerWorth(ref nStockTotal, ref nCash);
						nGrandTotal = nStockTotal + nCash;
						
						if (nGrandTotal > nMaxScore)
						{
							if (nPrevIndex >= 0)
								bSelected[nPrevIndex] = false;
							
							nPrevIndex = j;
							bSelected[nPrevIndex] = true;
									
							nMaxScore = nGrandTotal;
							nextPlayer = player;
						}
					}
				}

				players[i] = nextPlayer;
			}	
				
			// display player info	
			foreach (Player player in players)
			{
                string      sText;
                TableRow	row;
				TableCell	cell;

				nRow++;
			
				row = new TableRow();
				cell = new TableCell();

                sText = player.Name;

                if (player.Priority)
                    sText += " (Priority)";

                cell.Text = sText;
				row.Cells.Add(cell);

				// update public shares owned
				player.ResetShareIntraRoundInfo();
				player.UpdateShareTables();
			
				nStockTotal	= 0;
				nGrandTotal	= 0;
				
				// add place holder cells for each company
                for (int i = 0; i < Game.NumberOfCompanies; i++)
				{
					cell = new TableCell();
					cell.Text = "0";
					row.Cells.Add(cell);
				}
				
				// create placeholder cells for public companies
				foreach (PublicCompany company in game.PublicCompanies)
				{
					string	sCompany = company.Name;

					cell = row.Cells[company.Index + 1];
		
					if (player._nNumShares[company.Index] > 0)		// # shares
					{
						string sShares = player._nNumShares[company.Index].ToString();

						if (player._bPresShares[company.Index])		// has pres share?
							sShares += "P";

						cell.Text = sShares;
						//nStockTotal += company.StockMarketPosition.Value * player._nNumShares[company.Index];
					}
				}
				
				player.GetPlayerWorth(ref nStockTotal, ref nCash);
			
				// stock total
				cell = new TableCell();
				cell.Text = nStockTotal.ToString();
				row.Cells.Add(cell);

				// cash total
				cell = new TableCell();
				cell.Text = player.Cash.ToString();
				row.Cells.Add(cell);

				// grand total
				nGrandTotal = nStockTotal + player.Cash;
				cell = new TableCell();
				cell.Text = nGrandTotal.ToString();
				row.Cells.Add(cell);

				ResultsTable.Rows.AddAt(nRow, row);
			}

			// hide the cells and row for each company
			for (int i = 0; i < ResultsTable.Rows.Count; i++)
			{
                for (int j = 0; j < Game.NumberOfCompanies; j++)
					ResultsTable.Rows[i].Cells[j + 1].Visible = false;
			}
			
			// show the cells and row for each open company
			for (int i = 0; i < ResultsTable.Rows.Count; i++)
			{
                foreach (PublicCompany company in game.PublicCompanies)
                {
                    if (company.CompanyAvailable)
                        ResultsTable.Rows[i].Cells[company.Index + 1].Visible = true;
                }
			}
		}

		private void FillTableWithCompanyInfo()
		{
			Game	game = Global.getGame (this);;

			foreach (PublicCompany company in game.PublicCompanies)
			{
				int			nParPrice		= company.ParPrice;
				int			nCurrentValue	= company.MarketValue;
				string		sCompany		= company.Name;
                string      sText           = "";
                Button      button;
                TableCell   tableCell;
				
				// set company current stock market value
				sCompany = company.Name;
				sCompany += "CurrentValue";

				tableCell = (TableCell) ResultsTable.FindControl(sCompany); 
				
				if (game.GameOver && !game.CGRFormed)
				{
					if (company.Loans > 0)
					{
						nCurrentValue -= company.Loans * 10;	// deduct $10 per loan	
					
						if (nCurrentValue < 0)
							nCurrentValue = 0;
					}
				}

                if (company.StockMarketPosition != null)
                    tableCell.Text = nCurrentValue.ToString();
				
				// set company last dividend
				sCompany = company.Name;
                sCompany += "LastDividend";

				tableCell = (TableCell) ResultsTable.FindControl(sCompany); 
				
				if (company.StockMarketPosition != null)
                    sText = company.LastDividend.ToString();

                tableCell.Text = sText;

                // set company cash
                sCompany = company.Name;
                sCompany += "Cash";

                tableCell = (TableCell)ResultsTable.FindControl(sCompany);

                if (company.StockMarketPosition != null)
                    tableCell.Text = company.Cash.ToString();

                // set company escrow
                sCompany = company.Name;
                sCompany += "Escrow";

                tableCell = (TableCell)ResultsTable.FindControl(sCompany);

                if (company.StockMarketPosition != null)
                    sText = company.Escrow.ToString();

                tableCell.Text = sText;

                // set company loans
                sCompany = company.Name;
                sCompany += "Loans";

                tableCell = (TableCell)ResultsTable.FindControl(sCompany);

                if (company.StockMarketPosition != null)
                    tableCell.Text = company.Loans.ToString();

                // set company trains
                sCompany = company.Name;
                sCompany += "Trains";

                tableCell = (TableCell)ResultsTable.FindControl(sCompany);

                if (company.StockMarketPosition != null)
                {
                    foreach (Train train in company.Trains)
                    {
                        button = new Button();
                        button.Text = train.Name;

                        // denote borrowing a train
                        if (company.Name == "CGR" && company.BorrowingTrain)
                            button.Text += "-B";

                        button.Enabled = false;
                        tableCell.Controls.Add(button);
                    }
                }

                // set company par price
				sCompany = company.Name;
				sCompany += "ParPrice";

				tableCell = (TableCell) ResultsTable.FindControl(sCompany);
                
                if (company.StockMarketPosition != null)
                    tableCell.Text = nParPrice.ToString();
			}
		}

		protected void Back_Click(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			
			if (game.ViewGameStatusFromStockRound)
				Response.Redirect("StockRound.aspx");
			else
				Response.Redirect("OperatingRound2.aspx");
		}
	}
}

